package vtt.android.lichphatsongbongda.database;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import vtt.android.library.VttBaseApplication;
import vtt.android.library.utils.VttLog;
import vtt.android.library.utils.VttUtils;
import vtt.android.lichphatsongbongda.entities.TVScheduleItem;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class TVScheduleDAO {

	private static TVScheduleDAO instance = null;
	
	VttLog log = new VttLog("ResultDAO", VttBaseApplication.isDebuggable);
	// Database fields
	private SQLiteDatabase db;
	private MySQLiteOpenHelper dbHelper;
	
	public static TVScheduleDAO getInstance(Context context){
		if(instance == null){
			instance = new TVScheduleDAO(context);
		}
		return instance;
	}

	private TVScheduleDAO(Context context) {
		dbHelper = new MySQLiteOpenHelper(context);
	}

	public void open() throws SQLException {
		if(db == null) {
			db = dbHelper.getWritableDatabase();
		}
		
	}

	public void close() {
		dbHelper.close();
		db = null;
	}

	
	public void createCacheTable(SQLiteDatabase db) {
		String sql = " CREATE TABLE lps_bongda ( " 
				+ " thoigian text, "
				+ " trandau text, "
				+ " giaidau text, "
				+ " kenh text "
				+ ");";

		db.execSQL(sql);
	}
	
	// load cache data
	public List<TVScheduleItem> loadCacheData() {
		List<TVScheduleItem> tvSchedules = new ArrayList<TVScheduleItem>();
		// Select All Query
		String selectQuery = " SELECT thoigian, trandau, giaidau, kenh FROM lps_bongda ";
		Cursor cursor = db.rawQuery(selectQuery, null);
		// looping through all rows and adding to list
		String tempDay = "";
		if (cursor.moveToFirst()) {
			do {
				String thoigian = cursor.getString(0).trim();
				TVScheduleItem tvSchedule = new TVScheduleItem(
						thoigian, // thoi gian
						cursor.getString(1).trim(), // tran dau
						cursor.getString(2).trim(), // giai dau
						cursor.getString(3).trim()  // kenh
				);
				
				String compareDay = thoigian.split("-")[0];
				if(!tempDay.equals(compareDay)) {
					tempDay = compareDay;
					
					String headerTime = getFullDateTime(thoigian);
					tvSchedule.setHasHeader(true);
					tvSchedule.setHeaderTime(headerTime);
				}  
				
				tvSchedules.add(tvSchedule);
			} while (cursor.moveToNext());
		}
		return tvSchedules;
	}
	
	/**
	 * @param thoigian format input: dd/MM ex: 27/1
	 * @return full day output : Tue, 27/01/2015
	 */
	private String getFullDateTime(String thoigian) {
		int currentYear = Calendar.getInstance().get(Calendar.YEAR);
		try {
			return VttUtils.formatDate(currentYear + "/" + thoigian, "yyyy/dd/MM", "EEEE, dd/MM/yyy");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "Ngày " + thoigian;
	}

	// save cache data
	public void saveCacheData(List<TVScheduleItem> tvSchedules){
	    try {
	    	// delete all data before insert new cache data
	    	clearAllData();
	    	// begin batch insert
	    	db.beginTransaction();
	    	for (TVScheduleItem tvSchedule : tvSchedules) {
	    		ContentValues values = new ContentValues();
	    		values.put("thoigian", tvSchedule.getThoigian().trim());
	    		values.put("trandau", tvSchedule.getTrandau().trim());
	    		values.put("giaidau", tvSchedule.getGiaidau().trim());
	    		values.put("kenh", tvSchedule.getKenh().trim());
	    		
	    		db.insert("lps_bongda", null, values);
	    	}
	    	db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			db.endTransaction();
		}
	}
	
	public void clearAllData() {
		db.delete("lps_bongda", null, null);
	}
}
